package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.base.service.impl.UserServiceImpl;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;


    @Autowired
    private IUserService userService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForList(qo);

        for (CarPackageAudit audit : carPackageAudits) {
            audit.setServiceItem(serviceItemService.get(audit.getServiceItemId()));
            audit.setAuditor(userService.get(audit.getAuditorId()));
        }

        return new TablePageInfo<CarPackageAudit>(carPackageAudits);
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public void delete(Long id) {
        carPackageAuditMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateInstanceId(CarPackageAudit audit) {
        carPackageAuditMapper.updateInstanceId(audit);
    }


    // 获取流程图进度
    @Override
    public InputStream getProcessImageByAuditId(Long auditId) {
        CarPackageAudit audit = this.get(auditId);
        System.out.println("audit.getId() = " + audit.getId());
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getId());
        System.out.println("bpmnInfo = " + bpmnInfo);
        InputStream inputStream = null;
        // 使用流程文件讲代码方式画出来
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        // 1.审核中
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            Task task = taskService.createTaskQuery()
                    .processInstanceId(audit.getInstanceId()).singleResult();
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

            inputStream = generator.generateDiagram(model, activeActivityIds,
                    Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }else{
            //2：审核结束
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }
        return inputStream;
    }

    @Autowired
    private IServiceItemService serviceItemService;

    @Override
    public void cancelApply(Long id) {
        // 满足撤销状态
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw  new BusinessException("只有在审核记录才允许撤销");
        }
        // 套餐服务单项状态：初始化
        serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        // 套餐审核记录表状态：撤销
        carPackageAuditMapper.changStatus(id,CarPackageAudit.STATUS_CANCEL);
        // 流程实例删除
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"流程被撤销了");
    }

    // 审批实现
    @Override
    public void audit(Long id, Long auditStatus, String info) {
        // 满足条件判断(审核中和不为空)
        CarPackageAudit audit = this.get(id);
        if (audit ==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有在审核中状态时才可以进行审核");
        }
        String userName = ShiroUtils.getUser().getUserName();
        // 约定：2为同意
        if (auditStatus == 2) {
            info += "【"+userName+"同意】";
        }else {
            info += "【"+userName+"拒绝】";
        }
        audit.setInfo(audit.getInfo() +"<br>" +  info);
        // 流程审核记录表记录当前审核的时间
        audit.setAuditTime(new Date());

        // 执行当前节点
        Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId())
                .singleResult();

        // 设置审核查找的同意与否参数
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        // 设置审批备注
        taskService.addComment(task.getId(),audit.getInstanceId(),info);
        // 执行节点审批
        taskService.complete(task.getId());

        // 获取下一节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId())
                .singleResult();

        // 审核逻辑
        if (2==auditStatus) {
            // 审核通过
            // 1> 如果还有下一节点
            if (nextTask !=null) {
                // 流程审核记录当前审核人-（财务）
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }else{
                //2> 如果没有下一个节点-流程结束
                // 套餐服务单项状态：通过
                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                // 流程审核记录状态：通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        }else{
            // 审核拒绝
            // 套餐服务单项状态：初始化--- 建议加一个状态：审核拒绝，改动逻辑， 发起审核申请有2个状态可以
            serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
            //流程审核记录状态：审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }

}
